﻿using QG.FrontDesk.Core;
using QG.FrontDesk.DAL.IRepository;
using QG.FrontDesk.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace QG.FrontDesk.DAL.Repository
{
    public class VerificationCodeRepository : IVerificationCodeRepository
    {
        /// <summary>
        /// 新增验证码数据
        /// </summary>
        /// <param name="verificationCode"></param>
        /// <returns></returns>
        public int AddCode(VerificationCode verificationCode)
        {
            string sql = " INSERT INTO verificationCode VALUE(NULL, @CodeNum, @Email, @Phone, @ValidTime, @LoseTime)";
            return DapperDBHelper<VerificationCode>.Execute(sql, verificationCode); ;
        }

        /// <summary>
        /// 得到有效验证码
        /// </summary>
        /// <param name="verificationCode"></param>
        /// <returns></returns>
        public string GetCode(VerificationCode verificationCode)
        {
            string sql = "SELECT codeNum FROM verificationCode WHERE (Email=@Email OR Phone=@Phone) AND ValidTime<=NOW() AND LoseTime>NOW()";
            VerificationCode verification = DapperDBHelper<VerificationCode>.QuerySingleOrDefault(sql, verificationCode) ?? new VerificationCode();
            return verification.CodeNum;
        }

        /// <summary>
        /// 添加验证码
        /// </summary>
        /// <param name="verificationCode"></param>
        /// <returns></returns>
        public int AddVerificationCode(VerificationCode verificationCode)
        {

            string sql = "INSERT INTO `verificationcode`(`CodeNum`,`Email`,`Phone`,`ValidTime`,`LoseTime`)VALUES(@CodeNum, @Email, @Phone, @ValidTime, @LoseTime)";
            return DapperDBHelper<VerificationCode>.Execute(sql, verificationCode);

        }
        /// <summary>
        /// 查询验证码
        /// </summary>
        /// <param name="verificationCode"></param>
        /// <returns></returns>
        public int QueryVerificationCode(VerificationCode verificationCode)
        {
            string sql = "SELECT COUNT(1) FROM `verificationcode` WHERE `CodeNum` =@CodeNum AND (`Phone` = @Phone  OR `Email` = @Email) AND `LoseTime` >= NOW() ";
            return DapperDBHelper<VerificationCode>.Query(sql, verificationCode);
        }


    }
}


